package com.organization

import org.jgroups.JChannel
import org.jgroups.View
import org.jgroups.Message
import org.jgroups.ReceiverAdapter
import org.springframework.context.ApplicationContext
import org.codehaus.groovy.grails.web.context.ServletContextHolder
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes

/**
 * Created with IntelliJ IDEA.
 * User: inester
 * Date: 13.07.12
 * Time: 12:42
 * To change this template use File | Settings | File Templates.
 */
class JGroupsReceiver extends ReceiverAdapter{

    ApplicationContext ctx =
        ServletContextHolder.getServletContext().getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
    def localDataService = ctx.getBean('localDataService')

    private JChannel channel;
    static private JGroupsReceiver instance = null

    static public JGroupsReceiver getInstance(){
        if (!instance){
            instance = new JGroupsReceiver()
            instance.start()
        }
        return instance
    }

    public void receive(Message msg) {
        //procees server message
        def messMap = msg.getObject()
        if (messMap.source == "com.organization.Server" && messMap.node){
            //after update or delete any element we must flush all tree from cache and flush updated element from cache
            if (messMap.action == "update" || messMap.action == "delete"){
                localDataService.flushTreeCache("*")
                localDataService.flushElementCache(messMap.node)
            }
            //after add element we must flush all tree from cache
            else if (messMap.action == "add"){
                localDataService.flushTreeCache("*")
            }
        }
    }

    public void stop(){
        channel?.close()
    }

    private void start() throws Exception {
        channel=new JChannel();
        channel.setReceiver(this);
        channel.connect("com.organization.Cluster");
    }
}
